package com.ryzx.common.util;


import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * MD5加密/验证工具类
 *
 */
public class MD5Util {


    public static String encrypt(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            return new BigInteger(1,  md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encrypt(String plainText, String saltValue) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            md.update(saltValue.getBytes());
            return new BigInteger(1,  md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean valid(String text, String md5) {
        return md5.equals(encrypt(text)) || md5.equals(Objects.requireNonNull(encrypt(text)).toUpperCase());
    }
    public static boolean valid(String text, String md5,String saltValue) {
        return md5.equals(encrypt(text,saltValue));
    }


    public static void main(String[] args) {
        String plainText = "1";
        String saltValue = "admin123";
        System.out.println(encrypt(plainText));
        System.out.println(encrypt(plainText, saltValue));


    }
}